<template>
	<el-card>
		<template #header>
			<span style="font: 700 22px 微软雅黑;">学生管理</span>

			<div style="float: right; display: flex; gap: 20px;">

				<el-button plain @click="currentPage = 1; getData()">查询</el-button>
				<el-input v-model="searchValue" style="width: 240px" placeholder="请输入学号" clearable />

				<el-button type="primary" @click="insertFromVisible = true">
					<el-icon>
						<Plus />
					</el-icon>

					<span>新增学生</span>
				</el-button>

			</div>

		</template>

		<el-table :data="tableData" border height="525" size="large" stripe>
			<el-table-column fixed prop="id" label="ID" width="80" align="center" />
			<el-table-column prop="no" label="学号" width="110" align="center" />
			<el-table-column prop="name" label="姓名" width="100" align="center" />
			<el-table-column prop="gender" label="性别" width="70" align="center" />
			<el-table-column prop="phone" label="联系电话" width="130" align="center" />

			<el-table-column prop="classId" label="班级ID" width="80" align="center" />
			<el-table-column label="班级名称" width="200" align="center">
				<template #default="scope">
					{{ classList?.find(obj => scope.row?.classId === obj?.id)?.name || '' }}
				</template>
			</el-table-column>

			// 时间格式化
			<el-table-column prop="createTime" label="创建时间" width="170" align="center">
				<template #default="scope">
					{{ new Date(scope.row.createTime).toLocaleString() }}
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="最后一次更新时间" width="170" align="center">
				<template #default="scope">
					{{ new Date(scope.row.createTime).toLocaleString() }}
				</template>
			</el-table-column>

			<el-table-column fixed="right" label="操作" min-width="120" align="center">
				<template #default="scope">

					<el-button link type="primary" size="small"
						@click="updateFromVisible = true; updateFromData = JSON.parse(JSON.stringify(scope.row))">
						修改
					</el-button>

					<el-popconfirm title="不可逆操作，请谨慎执行！" @confirm="deleteSubmit(scope.row.id)">
						<template #reference>
							<el-button link type="primary" size="small">删除</el-button>
						</template>
					</el-popconfirm>

				</template>
			</el-table-column>

		</el-table>

		<el-row style="margin-top: 25px;">

			<el-col :span="4">
				<el-button type="primary" style="height: 40px;" @click="getData(); getClassList()">刷新页面</el-button>
			</el-col>

			<el-col :span="19">
				<el-pagination style="justify-content: end" :page-sizes="[5, 10, 20, 50]" background
					layout="total, sizes, prev, pager, next, jumper," v-model:total="currentTotal"
					v-model:page-size="currentPageSize" v-model:current-page="currentPage" @size-change="getData()"
					@current-change="getData()" />
			</el-col>

		</el-row>
	</el-card>


	<!-- 新增弹窗 -->
	<el-dialog v-model="insertFromVisible" title="新增" width="500" style="border-radius: 10px;">

		<el-form ref="insertFromRef" :model="insertFromData" style="margin: 0 auto;width: 350px;"
			:rules="insertFromRules">

			<el-form-item label="学号" prop="no">
				<el-input v-model="insertFromData.no" placeholder="请输入学号" />
			</el-form-item>

			<el-form-item label="学生姓名" prop="name">
				<el-input v-model="insertFromData.name" placeholder="请输入学生姓名" />
			</el-form-item>

			<el-form-item label="学生性别" prop="gender">
				<el-select v-model="insertFromData.gender" placeholder="请选择性别">
					<el-option label="男" :value="'男'" />
					<el-option label="女" :value="'女'" />
				</el-select>
			</el-form-item>

			<el-form-item label="联系电话" prop="phone">
				<el-input v-model="insertFromData.phone" placeholder="请输入联系电话" />
			</el-form-item>

			<el-form-item label="所属班级" prop="classId">
				<el-select v-model="insertFromData.classId" placeholder="请选择院系">
					<el-option v-for="item in classList as any" :label="item.id + ' : ' + item.name" :value="item.id" />
				</el-select>
			</el-form-item>

		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="insertFromVisible = false">关闭</el-button>
				<el-button type="primary" @click="insertSubmit" :loading="insertSubmitLoading">
					提交
				</el-button>
			</div>
		</template>
	</el-dialog>

	<!-- 修改弹窗 -->
	<el-dialog v-model="updateFromVisible" title="修改" width="500" style="border-radius: 10px;">

		<el-form ref="updateFromRef" :model="updateFromData" style="margin: 0 auto;width: 350px;"
			:rules="updateFromRules">

			<el-tooltip content="主键，不可修改" placement="top">
				<el-form-item label="院系ID" prop="id">
					<el-input v-model="updateFromData.id" placeholder="请输入院系名ID" disabled />
				</el-form-item>
			</el-tooltip>

			<el-form-item label="学号" prop="no">
				<el-input v-model="updateFromData.no" placeholder="请输入学生学号" />
			</el-form-item>

			<el-form-item label="学生姓名" prop="name">
				<el-input v-model="updateFromData.name" placeholder="请输入学生姓名" />
			</el-form-item>

			<el-form-item label="学生性别" prop="gender">
				<el-select v-model="updateFromData.gender" placeholder="请选择性别">
					<el-option label="男" :value="'男'" />
					<el-option label="女" :value="'女'" />
				</el-select>
			</el-form-item>

			<el-form-item label="联系电话" prop="phone">
				<el-input v-model="updateFromData.phone" placeholder="请输入联系电话" />
			</el-form-item>

			<el-form-item label="所属班级" prop="classId">
				<el-select v-model="updateFromData.classId" placeholder="请选择院系">
					<el-option v-for="item in classList as any" :label="item.id + ' : ' + item.name" :value="item.id" />
				</el-select>
			</el-form-item>

		</el-form>

		<template #footer>
			<div class="dialog-footer">
				<el-button @click="updateFromVisible = false">关闭</el-button>
				<el-button type="primary" @click="updateSubmit" :loading="updateSubmitLoading">
					提交
				</el-button>
			</div>
		</template>
	</el-dialog>


</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import axios, { HttpStatusCode } from 'axios';
import { ElMessage } from 'element-plus'

const tableData = ref([])
const classList = ref([])

onMounted(() => {
	getData()
	getClassList()
})

async function getData(page = currentPage.value, pageSize = currentPageSize.value) {
	try {
		const result = await axios.get(
			'/api/std/search',
			{
				params: {
					no: searchValue.value,
					page: page,
					pageSize: pageSize,
				}
			}
		);
		if (result.data.code === HttpStatusCode.Ok) {
			currentTotal.value = result.data.data.total;
			tableData.value = result.data.data.rows;
		} else {
			ElMessage({
				message: '获取数据失败！！！',
				type: 'error',
			})
		}
	} catch (err) {
		console.log(err);
	}
}

async function getClassList() {
	try {
		const result = await axios.get('/api/class/list');
		if (result.data.code === HttpStatusCode.Ok) {
			classList.value = result.data.data;
		} else {
			ElMessage({
				message: '获取数据失败！！！',
				type: 'error',
			})
		}
	} catch (err) {
		console.log(err);
	}
}


// 分页，相关属性，函数 
const currentTotal = ref(100);
const currentPage = ref(1);
const currentPageSize = ref(10);


// 新增弹窗，相关属性函数 ----------------------------------------------------------------
const insertFromRef = ref() // 表单实例（新增）
const insertFromVisible = ref(false) // 弹窗显示开关（新增）
const insertSubmitLoading = ref(false) // 提交加载状态开关（新增）
// 表单数据（新增）
const insertFromData = ref({
	no: '',
	name: '',
	gender: '男',
	phone: '',
	classId: null,
})
// 表单验证规则（新增）
const insertFromRules = {
	no: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' }
	],
	name: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' }
	],
	gender: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' }
	],
	phone: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' },
		{ patten: /^1[34578]\d{9}$/, min: 11, max: 11, message: '请输入正确的手机号', trigger: 'change' }
	],
	post: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' }
	],
	classId: [
		{ required: true, message: '必填项不应该为空', trigger: 'blur' }
	],
}



// 修改弹窗，相关属性函数 ----------------------------------------------------------------
const updateFromRef = ref() // 表单实例（修改）
const updateFromVisible = ref(false) // 弹窗显示开关（修改）
const updateSubmitLoading = ref(false) // 提交加载状态开关（修改）
// 表单数据（修改）
const updateFromData = ref({
	id: '',
	...insertFromData.value,
})
// 表单验证规则（修改）
const updateFromRules = {
	...insertFromRules,
}



// 接口访问 -----------------------------------------------------------------------------
// 新增
async function insertSubmit() {
	try {
		insertSubmitLoading.value = true;

		// 验证表单
		const validate = await insertFromRef.value.validate(e => e)
		if (!validate) {
			ElMessage({ message: '请检查表单', type: 'warning' })
			return
		}

		const data = {
			no: insertFromData.value.no,
			name: insertFromData.value.name,
			gender: insertFromData.value.gender,
			phone: insertFromData.value.phone,
			classId: insertFromData.value.classId,
		}
		const result = await axios.post('/api/std', data)
		if (result.data.code === HttpStatusCode.Ok) {
			getData()
			insertFromVisible.value = false
		} else if (result.data.code === 409 && result.data.msg === 'Duplicate_Key') {
			ElMessage({
				message: "新增数据失败：'" + data.no + "' 已被使用！！！",
				type: 'warning'
			})
		}
	} catch (err) {
		console.log(err);

		ElMessage({
			message: '提交失败！！！',
			type: 'error',
		})
	} finally {
		insertSubmitLoading.value = false
	}
}
// 修改
async function updateSubmit() {
	try {
		updateSubmitLoading.value = true;

		// 验证表单
		const validate = await updateFromRef.value.validate(e => e)
		if (!validate) {
			ElMessage({ message: '请检查表单', type: 'warning' })
			return
		}

		const data = {
			id: updateFromData.value.id,
			no: updateFromData.value.no,
			name: updateFromData.value.name,
			gender: updateFromData.value.gender,
			phone: updateFromData.value.phone,
			classId: updateFromData.value.classId,
		}
		const result = await axios.put('/api/std', data)
		if (result.data.code === HttpStatusCode.Ok) {
			getData()
		}
	} catch (err) {
		console.log(err);

		ElMessage({
			message: '提交失败！！！',
			type: 'error',
		})
	} finally {
		updateFromVisible.value = false
		updateSubmitLoading.value = false
	}
}
// 删除
async function deleteSubmit(id: number) {
	try {
		const arr = []
		arr.push(id)

		const result = await axios.delete('/api/std/' + arr)
		if (result.data.code === HttpStatusCode.Ok) {
			getData()
		}
	} catch (error) {
		console.log(error)
		ElMessage({
			message: '访问接口失败！！！',
			type: 'error',
		})
	}
}



// 查询，相关属性函数
const searchValue = ref('');

</script>